package com.odds.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReaderPageByUrl
{
    public String readerPageByUrl(String pageUrl)
    {
        URL url;
        String pageString = "";
        try
        {
            url = new URL(pageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "gbk"));
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            pageString = sb.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {

        }
        return pageString;
    }

    /**
     * 写入操作
     * 
     * @param filePath
     *            静态页面路径
     * @param fileStr
     *            网页内容
     * @throws Exception
     */
    public void writeStringToFile(String filePath, String fileStr) throws Exception
    {
        File file = new File(filePath);
        FileOutputStream fileout = new FileOutputStream(file);
        fileout.write(fileStr.getBytes("gbk"));
        fileout.close();
    }

    /**
     * 生成静态页面
     * 
     * @param pageUrl
     *            网址
     * @param filePath
     *            静态页面路径
     * @throws Exception
     */
    public void createStaticPage(String pageUrl, String filePath) throws Exception
    {
        // 获取网页内容
        String pageStr = readerPageByUrl(pageUrl);
        try
        {
            writeStringToFile(filePath, pageStr);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    // 测试
    public static void main(String[] args)
    {
        ReaderPageByUrl rb = new ReaderPageByUrl();
        
        String dayOdds = "http://odds.500wan.com/fenxi/ouzhi.php?id=";
        String[] parmas ={"298589","298594","283911"};
        
        String filePath = "E://project//odds//resource//";
        for (int i = 0; i < parmas.length; i++) {
			//String date = "20"+parmas[i].substring(0, 4)+"//";
				
			String newfn = filePath  + parmas[i] + ".html";
        	String pageUrl = dayOdds + parmas[i] ;
        	try
            {
                rb.createStaticPage(pageUrl, newfn);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
		}
        
    }

}
